package tr.richfacesext.util;

import java.util.Date;

import org.apache.commons.lang.StringUtils;
import org.joda.time.Period;

/**
 * 
 * @author mertcaliskan
 *
 */
public class FriendlyDateUtils {
	
	private static final String AGO_SUFFIX = "ago";	

	public static String convertElapsedTimeToPhrase(Date date) {
		Date currentDate = new Date();
		
		if (date != null) {
			Period period = new Period(date.getTime(), currentDate.getTime());
			
			StringBuffer buffer = new StringBuffer();
			int years = period.getYears();
			if (years > 0) {
				return formatDateItem(buffer, years, " year");
			}

			int months = period.getMonths();
			if (months > 0) {
				return formatDateItem(buffer, months, " month");
			}

			int weeks = period.getWeeks();
			if (weeks > 0) {
				return formatDateItem(buffer, weeks, " week");
			}

			int days = period.getDays();
			if (days > 0) {
				return formatDateItem(buffer, days, " day");
			}

			int hours = period.getHours();
			if (hours > 0) {
				return formatDateItem(buffer, hours, " hour");
			}
			int minutes = period.getMinutes();
			if (minutes > 0) {
				return formatDateItem(buffer, minutes, " minute");
			}

			int seconds = period.getSeconds();
			if (seconds > 0) {
				return formatDateItem(buffer, seconds, " second");
			}

			return "< 1 second " + AGO_SUFFIX;
		} 
		else {
			return StringUtils.EMPTY;
		}
		
	}
	
	private static String formatDateItem(StringBuffer buffer, int numberOfItems, String item) {
		buffer.append(numberOfItems).append(item);
		if (numberOfItems > 1) {
			buffer.append("s");
		}
		buffer.append(" " + AGO_SUFFIX);
		return buffer.toString();
	}
}